﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Windows.Forms;
using CosyTrade.Financial;
using CosyTrade.Store;
using CosyTrade.UI;
using DevExpress.XtraEditors.Controls;
using DevExpress.XtraGrid.Views.Grid.ViewInfo;

namespace CosyTrade.ClientForm
{
    public partial class CompanyProductSelect : UserControlBase
    {
        public event EventHandler<CompanyProductEventArgs> SelectedValue;

        public CompanyProductSelect()
        {
            InitializeComponent();
        }

        private void productCategoryDropdownControl1_ValueSelected(object sender, EventArgs e)
        {
            popboxProductCategory.EditValue = productCategoryDropdownControl1.SelectedProductCategory;
            popboxProductCategory.ClosePopup();
        }

        private void popboxProductCategory_CustomDisplayText(object sender, DevExpress.XtraEditors.Controls.CustomDisplayTextEventArgs e)
        {
            ProductCategoryBase productCategory = e.Value as ProductCategoryBase;
            e.DisplayText = productCategory == null ? "" : string.Format("{0}({1})", productCategory.CategoryChinese,
                                                                         productCategory.CategorySpanish);
        }

        #region Tab1View

        private void btnSearchCode_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            OnSearch();
        }

        private void btnSearchCode_KeyUp(object sender, KeyEventArgs e)
        {
            e.SuppressKeyPress = false;
            if (btnSearchCode.Text.Length < 3) return;
            OnSearch();
        }
        
        private void OnSelect()
        {
            CompanyProductView view = bindingSource1.Current as CompanyProductView;
            if (view == null || SelectedValue==null) return;
            SelectedValue(this, new CompanyProductEventArgs(view));
        }

        private void OnSearch()
        {
            IList<CompanyProductView> dataSource = 
                Operation.StoreManager.SearchProductView(btnSearchCode.Text, 
                GlobalInfo.CurrentCompany.PrimaryKey, 10);
            bindingSource1.DataSource = dataSource;
        }

        private void gridView1_KeyUp(object sender, KeyEventArgs e)
        {
            e.SuppressKeyPress = false;
            if (e.KeyCode == Keys.Enter) OnSelect();
        }

        private void gridView1_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button != MouseButtons.Left || e.Clicks < 2) return;

            GridHitInfo hitInfo = gridView1.CalcHitInfo(e.Location);
            if (hitInfo.InRow) OnSelect();
        }

        #endregion
        
        private void btnSave_Click(object sender, EventArgs e)
        {
            if (!CheckForm()) return;

            Product product = new Product();
            product.BarCode = txtBarcode.Text;
            product.CaptionChinese = txtChinese.Text;
            product.CaptionSpaish = txtSpanish.Text;
            product.Category = popboxProductCategory.EditValue as ProductCategoryBase;
            product.GrossWeight = double.Parse(txtTotalWeight.Text);
            if(!string.IsNullOrEmpty(btnSelectImage.Text) && File.Exists(btnSelectImage.Text))
            {
                string imgPath = Operation.DataStorage.SaveData(Functions.GetMiniImage(btnSelectImage.Text));
                product.ImagePath = imgPath;
            }
            product.Material = txtMaterial.Text;
            product.Memo = txtMemo.Text;
            product.ModuleInfo = txtModule.Text;
            Operation.ProductManager.CreateProduct(product);

            TradeProductExpandInfo expandInfo = new TradeProductExpandInfo();
            expandInfo.OnCompany = GlobalInfo.CurrentCompany;
            expandInfo.PackageCount = int.Parse(txtTotalPackageCount.Text);
            expandInfo.PackageUnitCount = int.Parse(txtPackageUnitCount.Text);
            expandInfo.Price = new ProductPrice();
            expandInfo.Price.CompanyStore = Operation.StoreManager.GetCompanyStore(
                GlobalInfo.CurrentCompany.PrimaryKey, product.PrimaryKey);
            expandInfo.Price.LogTime = 0;
            expandInfo.Price.Price = double.Parse(txtPrice.Text);
            expandInfo.Price.ShortCode = txtTradeCode.Text;
            expandInfo.Store = expandInfo.Price.CompanyStore;
            expandInfo.TotalBulk = txtBluk.Text;
            expandInfo.TotalWeight = double.Parse(txtTotalWeight.Text);
            expandInfo.TradeCode = txtTradeCode.Text;

            CompanyProductView view = Operation.StoreManager.CreateProduct(product.PrimaryKey,
                                                                           GlobalInfo.CurrentCompany.PrimaryKey,
                                                                           txtTradeCode.Text, int.Parse(txtStroe.Text),
                                                                           double.Parse(txtPrice.Text), expandInfo);

            ClearForm();
            if (SelectedValue != null) SelectedValue(this, new CompanyProductEventArgs(view));
        }

        private bool CheckForm()
        {
            if (Functions.ValueIsEmpty(txtBarcode, "请输入商品条形码")) return false;

            if (string.IsNullOrEmpty(txtChinese.Text))
            {
                Functions.ShowMessageBox("请输入商品中文名称");
                return false;
            }

            if (string.IsNullOrEmpty(txtSpanish.Text))
            {
                Functions.ShowMessageBox("请输入商品西班牙文名称");
                return false;
            }

            if (popboxProductCategory.EditValue == null)
            {
                Functions.ShowMessageBox("请选择商品所属分类");
                return false;
            }

            if (string.IsNullOrEmpty(txtFactroyModule.Text))
            {
                Functions.ShowMessageBox("请输入厂家型号");
                return false;
            }

            if (string.IsNullOrEmpty(txtModule.Text))
            {
                Functions.ShowMessageBox("请输入商品规格");
                return false;
            }

            if (string.IsNullOrEmpty(txtMaterial.Text))
            {
                Functions.ShowMessageBox("请输入商品质地");
                return false;
            }

            if (string.IsNullOrEmpty(txtGrossWeight.Text))
            {
                Functions.ShowMessageBox("请输入商品毛重");
                return false;
            }

            if (string.IsNullOrEmpty(txtBulk.Text))
            {
                Functions.ShowMessageBox("请输入商品体积");
                return false;
            }

            if (string.IsNullOrEmpty(txtTradeCode.Text))
            {
                Functions.ShowMessageBox("请输入商品编号");
                return false;
            }

            if (string.IsNullOrEmpty(txtStroe.Text))
            {
                Functions.ShowMessageBox("请输入商品库存");
                return false;
            }

            if (string.IsNullOrEmpty(txtBookCount.Text))
            {
                Functions.ShowMessageBox("请输入订货数量");
                return false;
            }
            
            if (string.IsNullOrEmpty(txtPrice.Text))
            {
                Functions.ShowMessageBox("请输入美金单价");
                return false;
            }

            if (string.IsNullOrEmpty(txtPackageUnitCount.Text))
            {
                Functions.ShowMessageBox("请输入装箱数");
                return false;
            }

            if (string.IsNullOrEmpty(txtTotalPackageCount.Text))
            {
                Functions.ShowMessageBox("请输入件数");
                return false;
            }

            if (string.IsNullOrEmpty(txtTotalWeight.Text))
            {
                Functions.ShowMessageBox("请输入商品总重量");
                return false;
            }

            if (string.IsNullOrEmpty(txtBluk.Text))
            {
                Functions.ShowMessageBox("请输入商品总体积");
                return false;
            }
           
            return true;
        }

        private void ClearForm()
        {
            txtBarcode.EditValue = string.Empty;
            txtBluk.EditValue = string.Empty;
            txtBookCount.EditValue = string.Empty;
            txtBulk.EditValue = string.Empty;
            txtChinese.EditValue = string.Empty;
            txtSpanish.EditValue = string.Empty;
            txtStroe.EditValue = string.Empty;
            txtMemo.EditValue = string.Empty;
            txtBookCount.EditValue = 0;
            txtFactroyModule.EditValue = string.Empty;
            txtGrossWeight.EditValue = 00;
            txtMaterial.EditValue = string.Empty;
            txtModule.EditValue = string.Empty;
            txtPackageUnitCount.EditValue = 0;
            txtPrice.EditValue = 0;
            txtTotalPackageCount.EditValue = 0;
            txtTotalWeight.EditValue = 0;
            txtTradeCode.EditValue = string.Empty;
            btnSelectImage.EditValue = string.Empty;
            popboxProductCategory.EditValue = null;
        }

        private void btnSelectImage_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            if (openFileDialog1.ShowDialog() != DialogResult.OK) return;
            btnSelectImage.EditValue = openFileDialog1.FileName;
        }

        private void rpiPrice1_CustomDisplayText(object sender, CustomDisplayTextEventArgs e)
        {
            ProductPrice price = e.Value as ProductPrice;
            e.DisplayText = price == null ? "0" : price.Price.ToString();
        }

        private void rpiPrice2_CustomDisplayText(object sender, CustomDisplayTextEventArgs e)
        {
            ProductPrice price2 = e.Value as ProductPrice;
            if (price2 == null)
            {
                e.DisplayText = "0";
                return;
            }
            ExchangeRate rate = CurrnetRate;
            if (rate == null)
            {
                e.DisplayText = "没设置默认汇率";
                return;
            }
            e.DisplayText = (price2.Price*rate.Exchange).ToString();
        }

        ExchangeRate currnetRate;
        private ExchangeRate CurrnetRate
        {
            get
            {
                if (currnetRate == null)
                    currnetRate =
                        Operation.FinancialSystem.GetCompanyDefaultExchangeRate(GlobalInfo.CurrentCompany.PrimaryKey);
                return currnetRate;
            }
        }

        private void rpiStore_CustomDisplayText(object sender, CustomDisplayTextEventArgs e)
        {
            CompanyStore store = e.Value as CompanyStore;
            if (store == null)
            {
                e.DisplayText = "0";
                return;
            }
            e.DisplayText = string.Format("{0}({1})", store.StoreCount, store.StoreCount - store.BookCount);
        }

        private void rpiProductName_CustomDisplayText(object sender, CustomDisplayTextEventArgs e)
        {
            CompanyStore store = e.Value as CompanyStore;
            if (store == null)
            {
                e.DisplayText = "";
                return;
            }
            e.DisplayText = string.Format("{0}", store.Products.Caption);
        }

    }

    public class CompanyProductEventArgs : EventArgs
    {
        private readonly CompanyProductView companyStoreView;

        public CompanyProductEventArgs(CompanyProductView companyStoreView)
        {
            this.companyStoreView = companyStoreView;
        }

        public CompanyProductView CompanyStoreView
        {
            get { return companyStoreView; }
        }
    }
}
